﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Configuration;

namespace Facebook.Configuration
{
    public class FacebookSection : ConfigurationSection
    {
        [ConfigurationProperty("applications")]
        [ConfigurationCollection(typeof(FacebookApplicationElement))]
        public FacebookApplicationElementCollection Applications
        {
            get { return (FacebookApplicationElementCollection)this["applications"]; }
            set { this["applications"] = value; }
        }

        [ConfigurationProperty("feedTemplateConfigSource")]
        public String FeedTemplateConfigSource
        {
            get { return (String)this["feedTemplateConfigSource"]; }
            set { this["feedTemplateConfigSource"] = value; }
        }

        private static FacebookSection _current;
        /// <summary>Gets a reference to the <see cref="FacebookSection" /> configured for the current application.</summary>
        public static FacebookSection Current
        {
            get
            {
                if (FacebookSection._current == null)
                {
                    var config = WebConfigurationManager.OpenWebConfiguration("~/");
                    var sections = config.Sections.OfType<ConfigurationSection>().Where(section => section.GetType() == typeof(FacebookSection)).ToList();
                    if (sections.Count > 1)
                    {
                        throw new ConfigurationErrorsException(String.Format("Too many instances of FacebookSection were found. Expected 1, found {0}.", sections.Count));
                    }
                    else if (sections.Count == 0)
                    {
                        throw new ConfigurationErrorsException("A configuration section of the type FacebookSection was not found in the current configuration.");
                    }
                    else
                    {
                        FacebookSection._current = (FacebookSection)sections.Single();
                    }
                }
                return FacebookSection._current;
            }
        }
    }
}